package com.easy.framework.common.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;

/**
 * 雪花算法生成ID
 * Author Yang HuiJIng  Email 1073602@qq.com
 */
@Component
public class IdGeneratorSnowflake {
    //工作ID (0~31)
    private long workerId = 0L;
    //数据中心ID (0~31)
    private long datacenterId = 1L;
    private Snowflake snowflake= IdUtil.createSnowflake(workerId,datacenterId);

    @PostConstruct
    public void init(){
        try{
            workerId= NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        }catch (Exception e){
            e.printStackTrace();
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized long snowflakeId(){
        return snowflake.nextId()-1000000000000000000L;
    }
    /**
     *
     * @param workerId 工作ID (0~31)
     * @param datacenterId 数据中心ID (0~31)
     * @return
     */
    public synchronized long snowflakeId(long workerId,long datacenterId){
        snowflake= IdUtil.createSnowflake(workerId,datacenterId);
        return snowflakeId();
    }

    public synchronized String snowflakeIdToString(){
        return String.valueOf(snowflakeId());
    }

    public synchronized String snowflakeIdToString(long workerId,long datacenterId){
        return ""+snowflakeId(workerId, datacenterId);
    }
}
